﻿using System;
using System.Collections.Generic;
using System.Linq;
using Note2.Db;
using SqlSugar;

public class SqlSugarHelper
{
    private static SqlSugarClient _db;

    static SqlSugarHelper()
    {
        // 配置SQLite连接字符串
        var connectionString = @"Data Source=../RemoteLogging.db;";

        // 初始化SqlSugarClient实例
        _db = new SqlSugarClient(new ConnectionConfig()
        {
            DbType = DbType.Sqlite,
            ConnectionString = connectionString,
            IsAutoCloseConnection = true,
            InitKeyType = InitKeyType.Attribute
        });
        _db.Aop.OnLogExecuting = (sql, pars) =>
        {
            Console.WriteLine(sql);
        };

        // 打开数据库连接
        _db.Open();
        // 检查数据库连接是否成功打开
        if (!_db.DbMaintenance.IsAnyTable("RemoteLogging"))
        {
            // 数据库连接打开失败后的处理
            SqlSugarHelper.Db.CodeFirst.InitTables(typeof(NoteRecord)); //建表
        }

    }

    public static SqlSugarClient Db => _db;

  
    public static T GetById<T>(string id) where T : class, new()
    {
        return _db.Queryable<T>().Where("ServerIP = @Id", new { Id = id }).First();
    }
    public static T GetById<T>(int id) where T : class, new()
    {
        return _db.Queryable<T>().Where("id = @Id", new { Id = id }).First();
    }

    public static List<T> GetAll<T>() where T : class, new()
    {
        return _db.Queryable<T>().ToList();
    }

    public static int Insert<T>(T entity) where T : class, new()
    {
        return _db.Insertable(entity).ExecuteReturnIdentity();
    }

    public static int Update<T>(T entity) where T : class, new()
    {
        return _db.Updateable(entity).ExecuteCommand();
    }

    public static int Delete<T>(T entity) where T : class, new()
    {
        return _db.Deleteable(entity).ExecuteCommand();
    }

    public static int ExecuteSql(string sql, params object[] parameters)
    {
        return _db.Ado.ExecuteCommand(sql, parameters);
    }
    public static int AddOrUpdated(NoteRecord entity)
    {
        var result = _db.Queryable<NoteRecord>().Where("ServerIP = @ServerIP", new { ServerIP = entity.ServerIP }).First();
        if (result!=null)
        {
            return _db.Updateable<NoteRecord>(entity).ExecuteCommand();
        }
        return _db.Insertable(entity).ExecuteReturnIdentity();
    }

}